package com.three.crm.page.user;


import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.binioter.guideview.Component;
import com.binioter.guideview.Guide;
import com.binioter.guideview.GuideBuilder;
import com.three.crm.MainActivity;
import com.three.crm.R;
import com.three.crm.base.BaseActivity;
import com.three.crm.component.MutiComponent;
import com.three.crm.component.SimpleComponent;
import com.three.crm.http.CommonResultCallBack;
import com.three.crm.require.AppRequireService;
import com.three.crm.util.AppManager;
import com.three.crm.util.PhoneUtils;
import com.three.crm.util.SignUtil;
import com.three.crm.util.XpopupUtil;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;

/**
 * 登录
 * created by lqd on 2023-11-20.
 */
public class LoginActivity extends BaseActivity {

    private final static int REQUEST_LOGIN = 100;
    private EditText etAccount,etPassword;
    private ImageView ivLogo;
    private Button btnLogin;

    @Override
    protected void initParms(Bundle bundle) {
        String token = AppManager.getToken();
        if (!TextUtils.isEmpty(token)) {
            startActivity(MainActivity.class);
            finish();
        }
    }

    @Override
    protected int bindLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initViews(View view, Bundle savedInstanceState) {
        etAccount = $(R.id.et_account);
        etPassword = $(R.id.et_password);
        ivLogo = $(R.id.iv_logo);
        btnLogin = $(R.id.btn_login);
    }

    @Override
    protected void setListener() {
        $(R.id.btn_login).setOnClickListener(this);
        $(R.id.tv_forgetpwd).setOnClickListener(this);
        $(R.id.iv_logo).setOnClickListener(this);
    }

    @Override
    protected void widgetClick(View v) {
        switch (v.getId()){
            case R.id.btn_login:
                onLogin();
                break;
            case R.id.tv_forgetpwd:
                onForgetPassword();
                break;
            case R.id.iv_logo:
                showGuideView();
                break;
        }
    }

    private void showGuideView() {
        GuideBuilder builder = new GuideBuilder();
        builder.setTargetView(ivLogo)
                .setAlpha(150)
               // .setAutoDismiss(false)
                .setHighTargetCorner(20)
                .setHighTargetPadding(10);
        builder.setOnVisibilityChangedListener(new GuideBuilder.OnVisibilityChangedListener() {
            @Override
            public void onShown() {
            }

            @Override
            public void onDismiss() {

            }
        });

        SimpleComponent simpleComponent = new SimpleComponent();
        simpleComponent.setOnNextListener(new SimpleComponent.OnNextListener() {
            @Override
            public void onNext(View v) {
                showGuideView2();
            }
        });

        builder.addComponent(simpleComponent);
        Guide guide = builder.createGuide();
        guide.show(LoginActivity.this);

    }

    private void showGuideView2() {
        final GuideBuilder builder1 = new GuideBuilder();
        builder1.setTargetView(btnLogin)
                .setAlpha(150)
                .setHighTargetGraphStyle(Component.CIRCLE);
        builder1.setOnVisibilityChangedListener(new GuideBuilder.OnVisibilityChangedListener() {
            @Override
            public void onShown() {
            }

            @Override
            public void onDismiss() {
                //showGuideView3();
            }
        });

        builder1.addComponent(new MutiComponent());
        Guide guide = builder1.createGuide();
        guide.setShouldCheckLocInWindow(false);
        guide.show(LoginActivity.this);
    }

    private void onLogin() {
        String account = etAccount.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        if (PhoneUtils.onCheckPhone(account,etAccount)) {
            if (TextUtils.isEmpty(password)) {
                showToast("请填写密码");
                return;
            }
            showLoading("正在努力登录中...");
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("mobile",account);
                jsonObject.put("password",password);
                jsonObject.put("timestamp",getTimestamp());
                String sign = SignUtil.genSign(jsonObject);
                jsonObject.put("sign",sign);
                AppRequireService.onLogin(this, REQUEST_LOGIN, jsonObject, new CommonResultCallBack(LoginActivity.this) {
                    @Override
                    public void onResult(String result, int requireCode) {
                        Log.i("TAG","RES="+result);
                        hideLoading();
                        if (result != null && result.length() > 0) {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                String token = jsonObject.getString("userToken");
                                int userId = jsonObject.getInt("userId");
                                int status = jsonObject.getInt("status");
                                int userType = jsonObject.getInt("user_type");
                                if (status == 1) {
                                    AppManager.setToken(token);
                                    AppManager.setUserId(userId);
                                    AppManager.setLevel(userType);
                                    AppManager.setLoginAccount(etAccount.getText().toString());
                                    startActivity(MainActivity.class);
                                    finish();
                                } else {
                                    onShowAccountAbnormal();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onConnectTimeOut(Call call, Exception e, int requireCode) {
                        hideLoading();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onFail(String msg, int requireCode) {
                        hideLoading();
                        showToast(msg);
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void onShowAccountAbnormal() {
        XpopupUtil.showOnce(this, "您的账号异常，可能是被注销了，请联系管理员处理!", new XpopupUtil.OnPopupOkListener() {
            @Override
            public void onPopupConfirm() {

            }
        });
    }

    private void onForgetPassword() {
        XpopupUtil.showOnce(this, "请联系管理员!", new XpopupUtil.OnPopupOkListener() {
            @Override
            public void onPopupConfirm() {

            }
        });
    }

    @Override
    protected void initData(Context mContext) {
        String loginAccount = AppManager.getLoginAccount();
        if (!TextUtils.isEmpty(loginAccount)) {
            etAccount.setText(loginAccount);
            etAccount.setSelection(loginAccount.length());
        }
    }
}